package com.mbbb.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mbbb.yygh.cmn.listener.DictListener;
import com.mbbb.yygh.cmn.mapper.DictMapper;
import com.mbbb.yygh.cmn.service.DictService;
import com.mbbb.yygh.common.exception.YyghException;
import com.mbbb.yygh.model.cmn.Dict;
import com.mbbb.yygh.vo.cmn.DictEeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 组织架构表 服务实现类
 * </p>
 *
 * @author mbbb
 * @since 2021-12-09
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Autowired
    private DictListener dictListener;

    //据dictCode获取下级节点
    @Override
    public List<Dict> getAllDataByDictCode(String dictCode) {
        //根据dictCode查询上级id
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code",dictCode);
        Dict idByDictCode = baseMapper.selectOne(wrapper);
        //根据等级id查询下级所有节点
        QueryWrapper<Dict> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("parent_id",idByDictCode.getId());
        List<Dict> dictList = baseMapper.selectList(wrapper1);

        return dictList;
    }

    //获取数据字典名称
    @Override
    public String getName(String dictCode, String value) {
        // 判断dictcode是否为空，空-value唯一，反之不唯一
        if (StringUtils.isEmpty(dictCode)) { //value唯一，直接查询
            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
            wrapper.eq("value",value);
            Dict dict = baseMapper.selectOne(wrapper);
            if (dict == null)
                throw new YyghException(20001,"查询失败");
            //返回对应名称
            return dict.getName();
        } else { //value不唯一，用dictCode查询
            //1.根据dictCode查询等级层id值
            QueryWrapper<Dict> dictCodeWrapper = new QueryWrapper<>();
            dictCodeWrapper.eq("dict_code",dictCode);
            Dict idByDictCode = baseMapper.selectOne(dictCodeWrapper);
            //2.根据上级id和value查询具体名称
            QueryWrapper<Dict> parentIdAndValueWrapper = new QueryWrapper<>();
            parentIdAndValueWrapper.eq("parent_id",idByDictCode.getId());
            parentIdAndValueWrapper.eq("value",value);
            Dict dict = baseMapper.selectOne(parentIdAndValueWrapper);
            //返回对应名称
            return dict.getName();
        }
    }

    //根据数据id查询子数据列表
    //SELECT * FROM dict WHERE parent_id = 1
    @Cacheable(value = "dict")
    @Override
    public List<Dict> findChildById(Long id) {
        //封装条件
        QueryWrapper<Dict> wrapper = new QueryWrapper();
        wrapper.eq("parent_id",id);
        List<Dict> dictList = baseMapper.selectList(wrapper);
        //hasChildren值，如果有子数据true，没有false
        //对dictList进行遍历，得到每个dict对象
        for (Dict dict : dictList) {
            //判断每个dict是否有下一层数据
            //根据dict的id查询下一层是否有数据
            //获取dict的id
            Long dictId = dict.getId();
            //查询判断
            boolean isChild = this.isHasChildren(dictId);
            //设置到dict对象里面
            dict.setHasChildren(isChild);
        }
        return dictList;
    }

    //查询dict是否有子数据
    private boolean isHasChildren(Long dictId) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",dictId);
        Integer count = baseMapper.selectCount(wrapper);
        // 3>0 返回true   0>0 返回false
        return count>0;
    }

    //数据字典导出
    @Override
    public void exportData(HttpServletResponse response) {
        try {
            //1.设置下载需要的参数
            //设置mime类型
            response.setContentType("application/vnd.ms-excel");
            //设置编码方式
            response.setCharacterEncoding("utf-8");
            //设置响应头
            //中文乱码处理，编码处理
            String fileName = URLEncoder.encode("数据字典", "utf-8");
            response.setHeader("Content-disposition","attachment;filename="+fileName+".xlsx");
            //2.查询数据库表dict的所有数据
            List<Dict> dictList = baseMapper.selectList(null);
            // Dict  DictEeVo
            // 把List<Dict>  变成  List<DictEeVo>
            List<DictEeVo> dictEeVoList = new ArrayList<>();
            //遍历 dictList.每个dict对象
            for (Dict dict : dictList) {
                /*//从每个dict获取数据
                Long id = dict.getId();
                Long parentId = dict.getParentId();
                String name = dict.getName();
                String value = dict.getValue();
                String dictCode = dict.getDictCode();

                //创建DictEeVo对象
                DictEeVo dictEeVo = new DictEeVo();
                //设置到dictEeVo里面
                dictEeVo.setId(id);
                dictEeVo.setParentId(parentId);
                dictEeVo.setName(name);
                dictEeVo.setValue(value);
                dictEeVo.setDictCode(dictCode);*/

                //创建DictEeVo对象
                DictEeVo dictEeVo = new DictEeVo();

                //使用工具类
                //把dict值 复制 到dictEeVo里面，不用像上面那么复杂
                BeanUtils.copyProperties(dict,dictEeVo);

                //放到list集合
                dictEeVoList.add(dictEeVo);
            }
            //3.使用EasyExcel进行写操作
            EasyExcel.write(response.getOutputStream(),DictEeVo.class)
                    .sheet("数据字典")
                    .doWrite(dictEeVoList);
        } catch (Exception e) {
            throw new YyghException(20001,"数据字典导出失败");
        }
    }

    //数据字典导入
    @CacheEvict(value = "dict",allEntries = true)
    @Override
    public void importData(MultipartFile file) {
        try {
            //调用EasyExcel方法
            EasyExcel.read(file.getInputStream(),
                           DictEeVo.class,
                           dictListener).sheet().doRead();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
